#include "stdafx.h"
#include "Container.h"

HWND Container::m_hWnd;

Container::Container(View *pView, HWND hWnd)
{
	m_hWnd = hWnd;
	m_pView = pView;
	m_bTrackingMouse = FALSE;
	m_pView->OnInvalidateRect += EventObject<View::OnInvalidateRectFunc>(this, &Container::OnInvalidateRect);
}

Container::~Container( void )
{

}

void Container::Render( HDC hdc, const RECT *lpRect )
{
	m_pView->Render(hdc, lpRect);
}

void Container::ViewMove( const POINT *lpSrc, const POINT *lpDst )
{
	POINT pt = {0, 0};
	m_pView->SetPos(&pt);
}

void Container::ViewResize( const SIZE *lpSrc, const SIZE *lpDst )
{
	m_pView->SetSize(lpDst);
}

void Container::MouseMove( const POINT *lpPoint )
{
	if (!m_bTrackingMouse)
	{
		TRACKMOUSEEVENT trackMouse = {0};
		trackMouse.cbSize = sizeof(trackMouse);
		trackMouse.hwndTrack = m_hWnd;
		trackMouse.dwFlags = TME_LEAVE;
		m_bTrackingMouse = TrackMouseEvent(&trackMouse);
	}

	TXCComPtr<View> pView;
	m_pView->ChildHitTest(lpPoint, &pView);

	if (m_pMouseEnter != pView) {
		if (m_pMouseEnter) {
			m_pMouseEnter->DoMouseLeave();
		}

		m_pMouseEnter = pView;
		if (m_pMouseEnter)
			m_pMouseEnter->DoMouseEnter();
	}
}

void Container::SetTimer( void * id, int delay )
{
	::SetTimer(m_hWnd, (UINT_PTR)id, delay, NULL);
}

void Container::KillTimer( void * id )
{
	::KillTimer(m_hWnd, (UINT_PTR)id);
}

void Container::OnInvalidateRect( const RECT *lpRect )
{
	::InvalidateRect(m_hWnd, NULL, FALSE);
}

void Container::Timer(void *id)
{
	bool bFind = false;
	m_pView->DoTimer(id, bFind);
}

void Container::MouseLeftDown( const POINT *lpPoint )
{
	SetCapture(m_hWnd);
	TXCComPtr<View> pView;
	m_pView->ChildHitTest(lpPoint, &pView);
	
	m_pMouseDown = pView;

	if (pView) {
		pView->DoMouseLeftDown(lpPoint);
	}
}

void Container::MouseLeftUp( const POINT *lpPoint )
{
//	TXCComPtr<View> pView;
//	m_pView->ChildHitTest(lpPoint, &pView);	
	ReleaseCapture();
	if (m_pMouseDown) {
		m_pMouseDown->DoMouseLeftUp(lpPoint);
		m_pMouseDown = NULL;
	}
}

void Container::MouseLeave()
{
	if (m_pMouseEnter) {
		m_pMouseEnter->DoMouseLeave();
	}
	m_pMouseEnter = NULL;
	m_bTrackingMouse = FALSE;
}